﻿using System;
using Didaku.Attributes;
using Didaku.Engine.Timeaxis.Kernel.Common;
using Didaku.Interface;
using NLog;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;

namespace Didaku.Engine.Timeaxis.Kernel.Initializes
{
    [EnvironmentItem(660, "启动日志服务。")]
    internal class LoggerInitialize : IInitializer
    {
        #region Implementation of IInitializer

        /// <summary>是否已经初始化
        /// </summary>
        public bool IsInitialized { get; private set; }

        /// <summary>执行初始化动作
        /// </summary>
        /// <param name="args">初始化的动作参数</param>
        public bool Initialize(params object[] args)
        {
            if (IsInitialized)
                return true;

            var config = new LoggingConfiguration();

            DefineColorConsoleTarget(ref config);
            DefineMongoDatabaseTarget(ref config);
            //DefineCsvFileTarget(ref config);

            LogManager.Configuration = config;

            Logger logger = LogManager.GetCurrentClassLogger();
            logger.Info("Nlog日志服务可用...");

            IsInitialized = true;
            OnInitialized(EventArgs.Empty);
            return true;
        }

        private static void DefineMongoDatabaseTarget(ref LoggingConfiguration config)
        {
            var target = new MongoDatabaseTarget();
            config.AddTarget("mongodb", target);
            var rule = new LoggingRule("*", LogLevel.Trace, target);
            config.LoggingRules.Add(rule);
        }

        private static void DefineColorConsoleTarget(ref LoggingConfiguration config)
        {
            var target = new ColoredConsoleTarget();
            target.Layout = "${date:format=HH\\:MM\\:ss} ${message}";
            config.AddTarget("console", target);
            var rule = new LoggingRule("*", LogLevel.Trace, target);
            config.LoggingRules.Add(rule);
        }

        private static void DefineCsvFileTarget(ref LoggingConfiguration config)
        {
            var target = new FileTarget();
            target.FileName = "${basedir}/file.txt";
            var csv = new CsvLayout();
            csv.Columns.Add(new CsvColumn("time", new CsvLayout()));
            csv.Columns.Add(new CsvColumn("message", new CsvLayout()));
            csv.Columns.Add(new CsvColumn("logger", new CsvLayout()));
            csv.Columns.Add(new CsvColumn("level", new CsvLayout()));
            target.Layout = csv;
            config.AddTarget("file", target);
            var rule = new LoggingRule("*", LogLevel.Trace, target);
            config.LoggingRules.Add(rule);
        }

        public event EventHandler InitializedEvent;

        protected virtual void OnInitialized(EventArgs e)
        {
            if (InitializedEvent != null)
                InitializedEvent(this, e);
        }

        #endregion
    }
}